<template>
  <div class="app">
    <el-tree
      :data="data"
      :props="defaultProps"
      default-expand-all
      :expand-on-click-node="false"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-dropdown @command="operateDept($event, data.id)">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="add">添加子部门</el-dropdown-item>
              <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
              <el-dropdown-item command="del">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </span>
    </el-tree>
    <!-- 添加组件 -->
    <department-add
      ref="addDept"
      :current-node-id="currentNodeId"
      :show-dialog.sync="showDialog"
      @updateDepartment="getDepartments"
    />
  </div>
</template>

<script>
import { getDepartments, deleteDepartment } from '@/apis/department.js'
import { transListToTreeData } from '@/utils/index.js'
import DepartmentAdd from './department-add.vue'
export default {
  components: {
    DepartmentAdd
  },
  data() {
    return {
      currentNodeId: null, // 当前的id
      showDialog: false, // 控制显示和隐藏
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      data: []
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      const { data } = await getDepartments()
      this.data = transListToTreeData(data.data, 0) // 转树形数据
    },
    // 操作部门方法
    operateDept(type, id) {
      if (type === 'add') {
        // 添加子部门
        this.showDialog = true
        this.currentNodeId = id
      } else if (type === 'edit') {
        // 编辑部门
        this.showDialog = true
        this.currentNodeId = id // 记录id 获取数据
        // 子组件获取数据
        // 父组件调用子组件的方法来获取数据
        this.$nextTick(() => {
          // 在回调内调用函数，防止数据传递异步，获取不到数据
          this.$refs.addDept.getDepartmentById() // this.$refs.addDept 等同于子组件的 this
        })
      } else {
        // 删除部门
        this.$confirm('您确定要删除该部门吗').then(async () => {
          await deleteDepartment(id)
          // 提示消息
          this.$message.success('删除部门成功')
          this.getDepartments()
        })
      }
    }
  }
}
</script>

<style scoped>
.app {
  padding: 30px 140px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 15px;
}
</style>